unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls, Buttons;

const
  W = 20;
  H = 10;
  N = 10;
  X = 0;
  Y = 0;

type
  TForm1 = class(TForm)
    img: TImage;
    st: TBitBtn;
    timer: TTimer;
    SB: TScrollBar;
    procedure FormCreate(Sender: TObject);
    procedure timerTimer(Sender: TObject);
    procedure SBChange(Sender: TObject);
    procedure stClick(Sender: TObject);
  private
    { Private declarations }
  public
    procedure Draw;
    { Public declarations }
  end;

var
  Form1: TForm1;
  mass: array of Integer;
  step, rn: Integer;
  flag: Boolean;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.Draw;
var i: Integer;
begin
  img.Canvas.Rectangle(img.ClientRect);
  for i:= 0 to N-1 do
  begin
    if (i <> step) and (i <> step+1) then
    begin
      img.Canvas.Rectangle(X+i*W, Y, X+(i+1)*W, Y+mass[i]*H);
    end else begin
      img.Canvas.Brush.Color:=clRed;
      img.Canvas.Rectangle(X+i*W, Y, X+(i+1)*W, Y+mass[i]*H);
      img.Canvas.Brush.Color:=clWhite;
    end;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  SetLength (mass, N);
  Randomize;
  step:=0;
  rn:=0;
  flag:=True;
end;

procedure TForm1.timerTimer(Sender: TObject);
var a: Integer;
begin
  if step = N-1-rn then
  begin
    rn:=rn+1;
    step:=0;
    if (rn = N-1) or (flag = true) then
    begin
      timer.Enabled:=false;
    end;
    flag:=True;
  end;
  if (mass[step] > mass[step+1]) then
  begin
    a:=mass[step];
    mass[step]:=mass[step+1];
    mass[step+1]:=a;
    flag:=False;
  end;
  Draw;
  step:=step+1;
end;

procedure TForm1.SBChange(Sender: TObject);
begin
  timer.Interval:=SB.Position*10;
end;

procedure TForm1.stClick(Sender: TObject);
var i: Integer;
begin
  Draw;
  timer.Enabled:=True;
  step:=0;
  rn:=0;
  flag:=True;
  for i:= 0 to N-1 do
  begin
    mass[i]:=Random(30);
  end;
end;

end.
